import {  memo, useEffect, useRef, useState } from "react";
import './private.scss'
import { Menu, message, Tooltip, type MenuProps  } from "antd";
import { UserOutlined, UserAddOutlined, UsergroupAddOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import http from "../../utils/http";
import api from "../../api";
import { ConfirmDialog, MyButton, MyDialog, MyInput, MySelect, UserInfoDlg } from "../../components";
import { createUserDropdownStyles, defaultTheme } from "../../static/styles/dropDown";
import PrivateChat from "./PrivateChat";
import kbAvatar from '../../static/imgs/kbAvatar.png'
import { useAppSelector } from "../../utils/storeHook/storeHook";

type MenuItem = Required<MenuProps>['items'][number];

interface friendT{
    friendship_id: string,
    user_id: string,
    friend_id: string,
    state: string,
    group_id: string,
    username: string,
    avatar_url: string,
}

interface groupT{
    group_id:string;
    group_name:string;
    position:number;
    user_id:string;
    friendList: friendT[];
}

const Private = memo(()=>{
    const styles = createUserDropdownStyles(defaultTheme)
    const userType = useAppSelector(state=>state.auth.userType)
    const privateChatUser = useAppSelector(state=>state.auth.privateChatUser)

    const [messageApi,ContextHolder] = message.useMessage();

    const [applicationList,setApplicationList] = useState<friendT[]>([])
    const [blacklist,setBlacklist] = useState<friendT[]>([])
    const [allFriendList,setAllFriendList] = useState<friendT[]>([])
    const [groupList,setGroupList] = useState<groupT[]>([])

    const [hoveredKey, setHoveredKey] = useState<string | null>(null);
    const [clickUserId,setClickUserId] = useState<string>('')
    const [userDtlDlgVis, setUserDtlDlgVis] = useState(false)
    const [confirmDelVis,setConfirmDelVis] = useState(false)
    const [actDirectChatId, setActDirectChatId] = useState('')
    // 添加好友
    const [addFriendDlgVis, setAddFriendDlgVis] = useState(false)
    const [addFriendId, setAddFriendId] = useState('')
    // 添加分组
    const [addGroupDlgVis,setAddGroupDlgVis] = useState(false)
    const [newGroupName,setNewGroupName] = useState('')
    // 添加到分组
    const [addToGroupDlgVis,setAddToGroupDlgVis] = useState(false)
    const [addToGroupId,setAddToGroupId] = useState('')

    const dropdownRef = useRef<HTMLDivElement>(null)

    function getFriendGroup(){
        http.post(api.friend.getFriendGroup,{}).then(res=>{
            const resData = res.data
            setGroupList(resData.groupList)
            setApplicationList(resData.applicationList)
            setBlacklist(resData.blackList)
            setAllFriendList(resData.allFriendList)
        })
    }

    function addFriendGroup(){
        if(userType=='guestUser') return messageApi.error('您无权限进行该操作')
        http.post(api.friend.addFriendGroup,{group_name:newGroupName}).then(()=>{
            messageApi.success('添加分组成功')
            getFriendGroup()
            setAddGroupDlgVis(false)
            setNewGroupName('')
        }).catch(err=>{
            messageApi.error(err.message)
        })
    }

    function changeFriendStatus(e:React.MouseEvent<HTMLDivElement, MouseEvent>,friend_id:string,status:string){
        e.stopPropagation()
        if(!friend_id || !status){
            return messageApi.error('参数错误')
        }
        http.post(api.friend.changeFriendStatus,{friend_id,status}).then(()=>{
            messageApi.success('操作成功')
            getFriendGroup()
        }).catch(err=>{
            messageApi.error(err.message)
        })
    }

    function deleteFriend(){
        if(!clickUserId) return messageApi.error('未选择删除好友')
        http.post(api.friend.deleteFriend,{friend_id:clickUserId}).then(()=>{
            messageApi.success('已删除该好友')
            getFriendGroup()
            setConfirmDelVis(false)
        }).catch(err=>{
            messageApi.error(err.message)
        })
    }

    function openPrivateChat(){
        http.post(api.message.getPrivateChatId,{friend_id:clickUserId}).then(res=>{
            const resData = res.data
            setActDirectChatId(resData.chat_id)
        }).catch(err=>{
            messageApi.error(err.message)
        })
    }

    const handleAddFriend = () => {
        if(userType=='guestUser') return messageApi.error('您无权限进行该操作')
        // 发送好友请求API调用
        if(!addFriendId) return messageApi.error('请输入用户ID')
        http.post(api.friend.addFriend,{friend_id:addFriendId}).then(()=>{
            messageApi.success('已发送好友申请')
        }).catch(err=>{
            messageApi.error(err.message)
        })
        setAddFriendDlgVis(false)
        setAddFriendId('')
    };

    function handleAddToGroupChange(value:string){
        setAddToGroupId(value)
    }

    function handleMoveToGroup(){
        if(!addToGroupId) return messageApi.error('请选择分组')
        http.post(api.friend.moveToGroup,{friend_id:clickUserId,group_id:addToGroupId}).then(()=>{
            messageApi.success('已移动到群组')
            setAddToGroupDlgVis(false)
            setAddToGroupId('')
            getFriendGroup()
        }).catch(err=>{
            messageApi.error(err.message)
        })
    }
    

    const menuItems: MenuItem[] = [
        {
            key: 'application',
            label: '申请列表',
            icon: <UserOutlined />,
            children: applicationList.map(friend=>
                ({ 
                    key: friend.friend_id, 
                    label: 
                        <div className="private_friend_item">
                            <span>{friend.username}</span>
                            <div className="private_friend_item_actions">
                                <Tooltip title='同意'>
                                    <div 
                                        className="private_friend_item_action"
                                        onClick={(e)=>changeFriendStatus(e,friend.user_id, 'accepted')} 
                                    >
                                        <CheckOutlined />
                                    </div>
                                </Tooltip>
                                <Tooltip title='拒绝'>
                                    <div 
                                        className="private_friend_item_action"
                                        onClick={(e)=>changeFriendStatus(e,friend.user_id, 'refused')} 
                                    >
                                        <CloseOutlined />
                                    </div>
                                </Tooltip>
                            </div>
                        </div>, 
                    icon: <img loading='lazy' src={friend.avatar_url || kbAvatar} alt="" />,
                }),
                    
            )
        },
        {
            key: 'all',
            label: '全部',
            icon: <UserOutlined />,
            children: allFriendList.map(friend=>
                ({ 
                    key: friend.friend_id, 
                    label: <div className="private_friend_item">
                            <span>{friend.username}</span>
                        </div>, 
                    icon: <img loading='lazy' src={friend.avatar_url || kbAvatar} alt="" /> }),
            ),
        },
        ...groupList.map(group=>({
            key:group.group_id,
            label:group.group_name,
            icon:<UserOutlined />,
            extra: '111',
            children:group.friendList.map(friend=>
                ({ key: group.group_id + friend.friend_id, label: <div>{friend.username}</div>, icon: <img loading='lazy' src={friend.avatar_url || kbAvatar} alt="" /> }),
            )
        })),
        {
            key: 'blacklist',
            label: '黑名单',
            icon: <UserOutlined />,
            children: blacklist.map(friend=>
                ({ key: friend.friend_id, label: <div>{friend.username}</div>, icon: <img loading='lazy' src={friend.avatar_url || kbAvatar} alt="" /> }),
            ),
        },
    ];


    const memuClick:MenuProps['onClick'] = (e)=>{
        setClickUserId(e.key)
        if(!dropdownRef.current) return
        dropdownRef.current.style.display = 'flex'
        dropdownRef.current.focus()
        const mouseEvent = e.domEvent as React.MouseEvent;
        const toBottomH = window.innerHeight - mouseEvent.clientY;
        const toTopH = mouseEvent.clientY;
        const clientH = dropdownRef.current.clientHeight
        if(toBottomH <= (clientH + 20)){
            if(toTopH <= (clientH + 20)){
                dropdownRef.current.style.top = '0'
                dropdownRef.current.style.bottom = 'auto'
            }else{
                dropdownRef.current.style.top = 'auto'
                dropdownRef.current.style.bottom = (toBottomH + 20) + `px`
            }
        }else{
            dropdownRef.current.style.top = (mouseEvent.clientY + 20) + 'px'
            dropdownRef.current.style.bottom = 'auto'
        }
        dropdownRef.current.style.left = mouseEvent.clientX + 'px'
    }

    function handleDropdownBlur(){
        if(!dropdownRef.current) return
        dropdownRef.current.style.display = 'none'
    }

    // 菜单项样式处理
    const getActionStyle = (key:string): React.CSSProperties => {
        const baseStyle = styles.listItem

        if (hoveredKey === key) {
            return {
                ...baseStyle,
                backgroundColor: '#3a3c42'
            };
        }

        return baseStyle;
    };

    useEffect(()=>{
        if(privateChatUser){
            http.post(api.message.getPrivateChatId,{friend_id:privateChatUser}).then(res=>{
                const resData = res.data
                setActDirectChatId(resData.chat_id)
            }).catch(err=>{
                messageApi.error(err.message)
            })
        }
    },[privateChatUser])

    useEffect(()=>{
        getFriendGroup()
    },[])
    return (
        <>
            {ContextHolder}
            <div className="private_box">
                <div className="private_left">
                    <div className='private_left_top'>
                        <div className='private_name'>好友</div>
                        <div className="private_actions">
                            <div className="private_action_btn" title="添加分组" onClick={()=>{
                                setNewGroupName('')
                                setAddGroupDlgVis(true)
                            }}>
                                <UsergroupAddOutlined />
                            </div>
                            <div className="private_action_btn" title="添加好友" onClick={()=>{
                                setAddFriendId('')
                                setAddFriendDlgVis(true)
                            }}>
                                <UserAddOutlined />
                            </div>
                        </div>
                    </div>
                    <div className='private_left_menu'>
                        <Menu
                            onClick={memuClick}
                            mode="inline"
                            defaultOpenKeys={['all']}
                            defaultSelectedKeys={[privateChatUser]}
                            items={menuItems}
                        />
                    </div>
                </div>
                <div className="private_right">
                    {actDirectChatId?
                    <PrivateChat key={actDirectChatId} chat_id={actDirectChatId} />
                    :<div className="private_right_empty">
                        <h2 className="private_empty_title">开始新的对话</h2>
                        <p className="private_empty_description">
                            选择一个好友开始私聊，或者添加新的联系人。私聊功能让您可以与朋友进行一对一的交流，分享想法和文件。
                        </p>
                        
                        {/* <div className="private_empty_friends_suggestions">
                            <h3 className="private_suggestions_title">你可能认识的人</h3>
                            <div className="private_suggestions_grid">
                                <div className="private_suggestion_card">
                                    <div className="private_suggestion_avatar">
                                        J
                                        <div className="private_suggestion_status online"></div>
                                    </div>
                                    <div className="private_suggestion_name">Jane Smith</div>
                                    <div className="private_suggestion_meta">12个共同好友</div>
                                    <button className="private_suggestion_button">发消息</button>
                                </div>
                                
                                <div className="private_suggestion_card">
                                    <div className="private_suggestion_avatar">
                                        M
                                        <div className="private_suggestion_status online"></div>
                                    </div>
                                    <div className="private_suggestion_name">Mike Johnson</div>
                                    <div className="private_suggestion_meta">8个共同好友</div>
                                    <MyButton type="primary">发消息</MyButton>
                                </div>
                            </div>
                        </div> */}
                    </div>}
                    
                </div>
            </div>
            <div 
                className="private_dropdown" 
                ref={dropdownRef} 
                tabIndex={0} 
                onBlur={()=>handleDropdownBlur()}
                style={styles.list} 
            >
                <div 
                    style={getActionStyle('k1')}
                    onMouseEnter={() => setHoveredKey('k1')}
                    onMouseLeave={() => setHoveredKey(null)}
                    onClick={openPrivateChat}
                >
                    发送私信
                </div>
                <div 
                    style={getActionStyle('k2')}
                    onMouseEnter={() => setHoveredKey('k2')}
                    onMouseLeave={() => setHoveredKey(null)}
                    onClick={()=>{
                        setAddToGroupId('')
                        setAddToGroupDlgVis(true)
                    }}
                >
                    添加到分组
                </div>
                <div 
                    style={getActionStyle('k3')}
                    onMouseEnter={() => setHoveredKey('k3')}
                    onMouseLeave={() => setHoveredKey(null)}
                    onClick={()=>setConfirmDelVis(true)}
                >
                    删除好友
                </div>
                <div 
                    style={getActionStyle('k4')}
                    onMouseEnter={() => setHoveredKey('k4')}
                    onMouseLeave={() => setHoveredKey(null)}
                    onClick={()=>{
                        setUserDtlDlgVis(true)
                    }}
                >
                    查看资料
                </div>
            </div>
            <MyDialog title="添加好友分组" visible={addGroupDlgVis} onClose={()=>setAddGroupDlgVis(false)}>
                <div className="private_dialog_box">
                    <div className="private_dialog_content">
                        <div className="private_input_group">
                            <label htmlFor="group_name">分组名称</label><div className="input_wrapper">
                            <MyInput 
                                id="group_name" 
                                value={newGroupName} 
                                onChange={(value:string)=>setNewGroupName(value)}
                                placeholder="输入分组名称"
                            />
                            </div>
                        </div>
                    </div>
                    <div className="private_dialog_footer">
                        <MyButton type="guest" onClick={()=>setAddGroupDlgVis(false)}>
                            取消
                        </MyButton>
                        <MyButton type="default" onClick={addFriendGroup}>
                            确定
                        </MyButton>
                    </div>
                </div>
            </MyDialog>
            <MyDialog title="添加好友" visible={addFriendDlgVis} onClose={()=>setAddFriendDlgVis(false)}>
                <div className="private_dialog_box">
                    <div className="private_dialog_content">
                        <div className="private_input_group">
                            <label htmlFor="group_name">好友id</label><div className="input_wrapper">
                            <MyInput 
                                id="group_name" 
                                value={addFriendId} 
                                onChange={(value:string)=>setAddFriendId(value)}
                                placeholder="输入好友id"
                            />
                            </div>
                        </div>
                    </div>
                    <div className="private_dialog_footer">
                        <MyButton type="guest" onClick={()=>setAddFriendDlgVis(false)}>
                            取消
                        </MyButton>
                        <MyButton type="default" onClick={handleAddFriend}>
                            发送请求
                        </MyButton>
                    </div>
                </div>
            </MyDialog>
            <MyDialog title={`添加"${allFriendList.find(item=>item.friend_id==clickUserId)?.username}"到分组`} visible={addToGroupDlgVis} onClose={()=>setAddToGroupDlgVis(false)}>
                <div className="private_dialog_box">
                    <div className="private_dialog_content">
                        <div className="private_input_group">
                            <label htmlFor="group_name">分组</label><div className="input_wrapper">
                            <MySelect 
                                id="group_name" 
                                value={addToGroupId} 
                                onChange={handleAddToGroupChange}
                                placeholder="选择分组"
                                options={[...groupList.map(group=>{
                                    return {value:group.group_id,label:group.group_name}
                                })]}
                            />
                            </div>
                        </div>
                    </div>
                    <div className="private_dialog_footer">
                        <MyButton type="guest" onClick={()=>setAddToGroupDlgVis(false)}>
                            取消
                        </MyButton>
                        <MyButton type="default" onClick={handleMoveToGroup}>
                            确定
                        </MyButton>
                    </div>
                </div>
            </MyDialog>
            <UserInfoDlg user_id={clickUserId} visible={userDtlDlgVis} onClose={() => setUserDtlDlgVis(false)} />
            <ConfirmDialog 
                visible={confirmDelVis} 
                onClose={()=>setConfirmDelVis(false)} 
                onConfirm={deleteFriend} 
                title="删除好友"
                tipText={`确定删除好友"${allFriendList.find(item=>item.friend_id==clickUserId)?.username}"吗？`}
            ></ConfirmDialog>
        </>
    )
})

export default Private